package com.byl.modules.core.service.impl;

import com.byl.common.modules.service.BaseServiceImpl;
import com.byl.modules.core.dao.AttachmentDao;
import com.byl.modules.core.dao.PosterDao;
import com.byl.modules.core.service.PosterService;
import com.byl.sdk.utils.MapUtils;
import com.byl.sdk.utils.UUIDUtils;
import com.byl.sdk.utils.UrlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Service
public class PosterServiceImpl extends BaseServiceImpl<PosterDao> implements PosterService {


    @Autowired
    AttachmentDao attachmentDao;




    @Override
    public int save(Map map) {
        String url = MapUtils.getValue(map, "url");
        if (!"".equals(url)) {
            //上传了附件
            // 添加mini路径
            map.put("miniurl", UrlUtils.getMiniUrl(url));
            map.put("type", 1);
            // 生成附件id
            map.put("attId", UUIDUtils.generateUUID());
            attachmentDao.save(map);
        } else {
            map.put("attId", "");
        }
        return super.save(map);
    }

    @Override
    public int update(Map map) {
        String url= MapUtils.getValue(map,"url");
        if(!"".equals(url)) {
            //处理产品之前没有附件
            deleteAttachment(MapUtils.getValue(map,"id"),MapUtils.getValue(map,"root"));
            //生产缩略图地址
            map.put("miniurl",UrlUtils.getMiniUrl(url));
            //直接修改附件
            attachmentDao.update(map);
        }
        return super.update(map);
    }


    /**
     * 删除指定产品的附件
     * @param id 产品id
     * @param root  服务器路径
     */
    private void deleteAttachment(String id,String root) {
        Map attMap = baseDao.queryAttachmentByPosterId(id);
        if (null != attMap) {//说明有附件
            //获取原图
            String url= MapUtils.getValue(attMap,"url");
            //删除原图
            removeFile(root+url);
            //获取缩略图
            String miniurl=MapUtils.getValue(attMap,"miniurl");
            //删除缩略图
            removeFile(root+miniurl);
        }
    }

    /**
     * 删除文件
     * @param path
     */
    private void removeFile(String path){
        File file=new File(path);
        if(file.exists())
            file.delete();
    }

    @Override
    public int delete(String id) {
        Map map = new HashMap();
        map.put("id", id);
        map.put("isdel", "1");
        return baseDao.update(map);
    }

}
